package net.my.msn.web;

import java.util.Collection;
import java.util.Iterator;

import net.my.msn.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserListController {
	@Autowired
	UserService userService;

	public String authorityBySecurity() {
		Object obj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		String role = null;
		Collection<GrantedAuthority> c = null;
		if (obj instanceof UserDetails) {
			c = ((UserDetails) obj).getAuthorities();
		}
		Iterator<GrantedAuthority> iter = c.iterator();
		while (iter.hasNext()) {
			role = iter.next().getAuthority();
		}
		return role;
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public ModelAndView users() {
		ModelMap modelMap = new ModelMap();
		boolean isAdmin = false;
		if (authorityBySecurity().equals("ROLE_ADMIN"))
			isAdmin = true;
		modelMap.addAttribute("isAdmin", isAdmin);
		modelMap.addAttribute("userList", userService.userList());
		return new ModelAndView("users", modelMap);

	}

	@RequestMapping(value = "/access{user_id}", method = RequestMethod.GET)
	public String userAccess(@PathVariable("user_id") Long userId) {
		userService.userAccess(userId);
		return "redirect:users";
	}

}
